﻿using FlashPay.DAO.Interface;
using FlashPay.EF;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Request;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace FlashPay.DAO.Impl
{
    /// <summary>
    /// 功能权限记录数据接口
    /// </summary>
    /// <remarks>2018-07-09 immi 创建</remarks>
    public class PermissionDaolmpl: IDisposable, PermissionDao
    {
        #region 注入
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public PermissionDaolmpl(FlashPayContext context)
        {
            _context = context;
        }
        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取权限功能
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Permission</returns>
        public Permission Get(int id)
        {
            return _context.Permission.Where(x => x.Pid == id).FirstOrDefault();
        }

        //查詢所有功能列表
        public List<Permission> GetList(PermissionQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<Permission>();

            if (query.NoEqualId.HasValue)
            {
                where = where.And(c => c.Pid != query.NoEqualId.Value);
            }
            //权限名称
            if (!string.IsNullOrEmpty(query.PName))
            {
                where = where.And(c => c.PName == query.PName);
            }

            //权限代码
            if (!string.IsNullOrEmpty(query.PCode))
            {
                where = where.And(c => c.PCode == query.PCode);
            }

            if (query.NodeType.HasValue)
            {
                where = where.And(c => c.NodeType != query.NodeType.Value);
            }

            var list = _context.Permission.Where(where.Compile()).ToList();

            return list;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Permission model)
        {
            //将对象加入到数据上下文的UserInfo集合中
            _context.Permission.Add(model);
            //调用数据上下文的保存方法，将对象存数数据库
            var resultId = _context.SaveChanges();

            return resultId;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public bool Update(Permission model)
        {
            bool result = false;

            var permission = _context.Permission.Find(model.Pid);
            if (permission != null)
            {
                permission.Pid = model.Pid;
                permission.PParent = model.PParent;
                permission.PName = model.PName;
                permission.PCode = model.PCode;
                //permission.PControllerName = model.PControllerName;
                //permission.PActionName = model.PActionName;
                permission.NodeType = model.NodeType;
                permission.SortNo = model.SortNo;
                permission.Hide = model.Hide;

                _context.Entry<Permission>(permission);
                _context.SaveChanges();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <returns></returns>
        public bool Delete(int id)
        {

            //实例化一个UserInfo对象，并指定Id的值
            Permission permission = new Permission()
            {
                Pid = id
            };
            //将UserInfo附加到上下文对象中，并获得EF容器的管理对象
            var result = _context.Entry<Permission>(permission);
            //设置该对象的状态为删除
            result.State = EntityState.Deleted;
            //保存修改
            _context.SaveChanges();

            return true;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public bool UpdateStatus(UpdateStatusRequest request)
        {
            //官方推荐的修改方式（先查询，再修改）
            var model = _context.Permission.Where(p => p.Pid.Equals(request.Id)).FirstOrDefault();
            if (model != null)
            {
                model.Hide = request.Status;
                int row = _context.SaveChanges();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }

        /// <summary>
        /// 获取功能权限列表
        /// </summary>
        /// <param name="sysNoList">系统编号列表</param>
        /// <returns>功能权限列表</returns>
        public List<Permission> GetListByIds(List<int> ids)
        {
            return _context.Permission.Where(p => ids.Contains(p.Pid)).ToList();
        }

        /// <summary>
        /// 获取功能权限列表
        /// </summary>
        /// <param name="sysNoList">权限编号列表</param>
        /// <returns>功能权限列表</returns>
        public List<Permission> GetListByCodes(List<string> codes)
        {
            return _context.Permission.Where(p => codes.Contains(p.PCode)).ToList();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<Permission></returns>
        public PagedList<Permission> GetPager(PermissionQuery query)
        {

            //多条件查询
            var where = PredicateBuilder.True<Permission>();
            //权限名称
            if (!string.IsNullOrEmpty(query.PName))
            {
                where = where.And(c => c.PName.Contains(query.PName));
            }
            //权限代码
            if (!string.IsNullOrEmpty(query.PCode))
            {
                where = where.And(c => c.PCode.Contains(query.PCode));
            }
            if (query.NodeType.HasValue)
            {
                where = where.And(c => c.NodeType == query.NodeType.Value);
            }
            var row = _context.Permission.Where(where.Compile()).OrderBy(p => p.PCode).ThenBy(p=>p.SortNo).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();
            var count = _context.Permission.Where(where.Compile()).Count();

            var list = new PagedList<Permission>
            {
                TData = row,
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = count
            };

            return list;
        }
    }
}
